<!--
 * @Author: lirl
 * @Date: 2023-04-05 19:08:07
 * @Description: file content
-->
<template>
  <div :class="customClass">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <template v-for="(breadcrumb, index) in breadcrumbs">
        <!-- 如果breadcrumb的to字段有效则为可跳转面包屑 -->
        <el-breadcrumb-item v-if="breadcrumb.to" :key="index" :to="breadcrumb.to">
          {{breadcrumb.name}}
        </el-breadcrumb-item>
        <!-- 否则为不可跳转面包屑 -->
        <el-breadcrumb-item v-else :key="breadcrumb.name">
          {{breadcrumb.name}}
        </el-breadcrumb-item>
      </template>
    </el-breadcrumb>
  </div>
</template>

<script>
import { isUndefined } from 'lodash-es';
import { mapState, mapMutations, mapActions } from 'vuex';

export default {
  props: {
    customClass: {
      type: String,
      default: 'u-breadcrumb'
    },
  },
  computed: {
    // 使用mapState将state以计算属性映射到页面中
    ...mapState({
      breadcrumbs: state => state.breadcrumb.breadcrumbs
    })
  },
  mounted() {
    // 从路由元数据中获取面包屑字符串
    const { breadcrumb } = this.$route.meta;
    // 如果路由元数据有breadcrumb字符串,则通过元数据中的breadcrumb字符串获取面包屑路径
    if (!isUndefined(breadcrumb)) {
      this.getBreadcrumbByString(breadcrumb);
    } else {
      // 构建新面包屑路径数组
      const newBreadcrumbs = [{ name: this.$route.meta.name, to: this.$route.to }];
      // 将新面包屑路径数组添加到面包屑数组中(自动去除)
      this.addBreadcrumb(newBreadcrumbs);
    }
  },
  methods: {
    // 使用mapMutations将mutation以事件形式映射到页面中
    ...mapMutations({
      setBreadcrumbs: 'breadcrumb/SET_BREADCRUMBS'
    }),
    // 使用mapActions将actions以事件形式映射到页面中
    ...mapActions({
      addBreadcrumb: 'breadcrumb/addBreadcrumb'
    }),
    /**
     * 通过面包屑字符串获取面包屑
     * @param {String} 面包屑字符串
     */
    getBreadcrumbByString(breadcrumb) {
      // 通过#号将面包屑字符串转为面包屑路径名称数组
      const breadcrumbNameList = breadcrumb.split('#');
      // 将面包屑路径名称数组转为面包屑路径数组
      const breadcrumbList = breadcrumbNameList.map(it => ({
        name: it,
        to: ''
      }));
      breadcrumbList[breadcrumbList.length - 1].to = this.$route.path;
      // 使用mutations将面包屑路径数组添加到vuex的面包屑路径数组中
      this.setBreadcrumbs(breadcrumbList);
    }
  }
};
</script>
<style lang="scss">
@import '~@/assets/style/variables.scss';

.u-breadcrumb {
  text-align: left;
  &::before {
    content: '';
    background-color: $main-color;
    width: 2px;
    height: 12px;
    display: block;
    margin-top: 19px;
    float: left;
  }
  /*1108新增 */
  .el-breadcrumb {
    padding-left: 10px;
    line-height: $siderbar-menu-item-height;
    .el-breadcrumb__inner {
      color: #97a8be;
      font-size: 14px;
    }
    i {
      margin: 0 2px;
      margin-left: -1px;
      font-size: 12px;
    }
  }
  .el-divider {
    margin: 0;
  }
}
</style>
